package mfuny.ggongal.admin.contents;

import java.io.File;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

import mfuny.ggongal.admin.Server;
import mfuny.ggongal.admin.advertisers.AdvertiserDao;
import mfuny.ggongal.admin.debug.Debug;
import mfuny.ggongal.admin.gift.GiftDao;

import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.ibatis.sqlmap.client.SqlMapClient;

public class ContentService {
	SqlMapClient sqlMapper;
	
	ModelAndView mav;
	List<AdvertiserDao> advList;
	
//	Class<?> c;
//	Method m;
	MultipartFile file;
	List<MultipartFile> files;
	GiftDao giftClass;
	
	Random ran;
	
	public ContentService() throws Exception {
		sqlMapper = Server.getSqlMapper( );
		
		mav = new ModelAndView();
		advList = new ArrayList<AdvertiserDao>();
		files = new ArrayList<MultipartFile>();
//		c = Class.forName( "mfuny.ggongal.admin.contents.ContentDao" );
		giftClass = new GiftDao();
		ran = new Random();
	}
	
	public ModelAndView contentsList() throws Exception {
		mav.clear();
		mav.setViewName("/contents/contentsList.ga");
		return mav;
	}
	
	@SuppressWarnings("unchecked")
	public ModelAndView contentsList_detail(String jsonParam) throws Exception {
		JSONObject jsonParams = (JSONObject) JSONValue.parse(jsonParam);
		int pageNum = jsonParams.get("num") instanceof Integer ? (Integer)jsonParams.get("num") : (int)(long)(Long)jsonParams.get("num");
		int pageSize = jsonParams.get("pageSize") instanceof Integer ? (Integer)jsonParams.get("pageSize") : (int)(long)(Long)jsonParams.get("pageSize");
		jsonParams.put("num", pageNum <= 0 ? 1 : pageNum * pageSize - pageSize );
		
		List<HashMap<String, Object>> resultList = sqlMapper.queryForList("con_selectByIdForAdmin", jsonParams);
		int totalCount = (Integer) sqlMapper.queryForObject("con_countAllById", (String)jsonParams.get("co_id"));
		mav.clear();
		mav.setViewName("/contents/contentsList_detail");
		mav.addObject("resultList", resultList);
		mav.addObject("totalCount", totalCount);
		mav.addObject("pageNum", pageNum);
		return mav;
	}
	
	@SuppressWarnings( "unchecked" )
	public ModelAndView regContentsForm() throws Exception {
		advList = sqlMapper.queryForList( "adv_selectNoOut", null );
		mav.clear( );
		mav.setViewName( "/contents/regContentsForm.ga" );
		mav.addObject( "resultList", advList );
		return mav;
	}
	
	@SuppressWarnings("unchecked")
	public ModelAndView modifyContentsForm(int no) throws Exception {
		HashMap<String, Object> tempParam = (HashMap<String, Object>) sqlMapper.queryForObject("con_selectByNo", no);
		tempParam.put("gift2", tempParam.get("gift2") == null || tempParam.get("gift2").equals("") ? null : tempParam.get("gift2"));
		tempParam.put("gift3", tempParam.get("gift3") == null || tempParam.get("gift3").equals("") ? null : tempParam.get("gift3"));
		
		HashMap<String, Object> resultClass = (HashMap<String, Object>) sqlMapper.queryForObject("con_selectModify", tempParam);
		mav.clear();
		mav.setViewName("/contents/modifyContentsForm.ga");
		mav.addObject("resultClass", resultClass );
		return mav;
	}
	
	public ModelAndView modifyContents(ContentDao conDao) throws Exception {
		//기존 컨텐츠 정보 가져오기.
//		ContentDao beforeCon = (ContentDao) sqlMapper.queryForObject("con_selectByNoAll", conDao.getNo());
		
		//새로운 이미지 파일 저장 및 변경할 파일이 무엇인지 가져오기.
//		List<Integer> imgNoForChange = setFile(conDao, conDao.getFiles());
		
		//수정할 경품정보 가져오기.
//		HashMap<String, Object> gifts = getGiftForUpdate(conDao, beforeCon);
		
		
		return contentsList();
	}
	
	@SuppressWarnings("unchecked")
	public void regContents( ContentDao conDao ) throws Exception {
		List<GiftDao> giftList = new ArrayList<GiftDao>();
		try {
			sqlMapper.startTransaction( );
			sqlMapper.startBatch( );
			setFile2( conDao, conDao.getFiles( ) );
			
			files = conDao.getGiftfiles( );
			for ( int i = 0; i < files.size( ); i++ ) {
				file = files.get( i );
				if ( file.getOriginalFilename( ) == null || file.getOriginalFilename( ) == "" ) { continue; }
				Class c = conDao.getClass();
				Method m = c.getMethod( "getGift" + (i + 1) );
				GiftDao tempGiftClass = new GiftDao();
				tempGiftClass.setId( String.valueOf( System.currentTimeMillis( ) ) + i );
				tempGiftClass.setName( (String) m.invoke( conDao ) );
				tempGiftClass.setPrice( (Integer) c.getMethod( "getGift" + (i+1) + "_price" ).invoke( conDao ) );
				tempGiftClass.setImg_capacity(file.getSize());
				tempGiftClass.setImg_oriname( file.getOriginalFilename( ) );
				tempGiftClass.setImg_savname( String.valueOf( System.currentTimeMillis( ) ) + "_" + ran.nextInt( 100 ) + "_" + i + "_" + conDao.getCo_id() + ".jpg" );
				
				m = c.getMethod( "setGift" + (i + 1), new Class[]{ String.class } );
				m.invoke( conDao, tempGiftClass.getId( ) );
				giftList.add( tempGiftClass );
			}
			
			sqlMapper.update( "con_insert", conDao );
			int contents_no = ( sqlMapper.queryForObject( "con_selectLastNo", null ) == null ? 1 : ((Integer)sqlMapper.queryForObject( "con_selectLastNo", null )) + 1 );
			
			for ( int i = 0; i < giftList.size( ); i++ ) {
				giftClass = giftList.get( i );
				giftClass.setContents_no( contents_no );
				sqlMapper.update( "gift_insert", giftClass );
				files.get( i ).transferTo( new File( Server.filePath + giftClass.getImg_savname( )) );
			}
			sqlMapper.executeBatch( );
			sqlMapper.commitTransaction( );
		} catch ( Exception e ) {
			Debug.toDebugFile(e, "regContents");
		} finally {
			sqlMapper.endTransaction( );
		}
	}
	
	@SuppressWarnings({ "unchecked", "unused" })
	private List<Integer> setFile( ContentDao dao, List<MultipartFile> list ) throws Exception {
		List<Integer> changeImgNo = new ArrayList<Integer>();
		Class c = dao.getClass();
		if ( list.size( ) > 0 ) {
			for ( int i = 0; i < list.size( ); i++ ) {
				file = list.get( i );
				if ( file.getOriginalFilename( ) == null || file.getOriginalFilename( ) == "" ) { continue; }
				Method m = c.getMethod( "setImgcontents"+ (i+1) +"_oriname", new Class[]{String.class} );
				m.invoke( dao, new Object[]{ file.getOriginalFilename( ) } );
				m = c.getMethod( "setImgcontents"+ (i+1) +"_savname", new Class[]{String.class} );
				String savname = String.valueOf( System.currentTimeMillis( ) ) + "_" + ran.nextInt( 100 ) + "_" + i + "_" + dao.getCo_id() + ".jpg";
				m.invoke( dao, new Object[]{ savname } );
				m = c.getMethod("setImgcontents" + (i+1) + "_capacity", new Class[]{Long.class} );
				m.invoke( dao, new Object[] {file.getSize()} );
				
				file.transferTo( new File( Server.filePath + savname) );
				changeImgNo.add(i + 1);
			}
		}
		return changeImgNo;
	}
	//capacity 메서드를 찾기 못하는 신의 장난 때문에 임시처리...
	@SuppressWarnings("unchecked")
	private List<Integer> setFile2( ContentDao dao, List<MultipartFile> list ) throws Exception {
		List<Integer> changeImgNo = new ArrayList<Integer>();
		Class c = dao.getClass();
		if ( list.size( ) > 0 ) {
			for ( int i = 0; i < list.size( ); i++ ) {
				file = list.get( i );
				if ( file.getOriginalFilename( ) == null || file.getOriginalFilename( ) == "" ) { continue; }
				Method m = c.getMethod( "setImgcontents"+ (i+1) +"_oriname", new Class[]{String.class} );
				m.invoke( dao, new Object[]{ file.getOriginalFilename( ) } );
				m = c.getMethod( "setImgcontents"+ (i+1) +"_savname", new Class[]{String.class} );
				String savname = String.valueOf( System.currentTimeMillis( ) ) + "_" + ran.nextInt( 100 ) + "_" + i + "_" + dao.getCo_id() + ".jpg";
				m.invoke( dao, new Object[]{ savname } );
				
				switch(i) {
				case 0:
					dao.setImgcontents1_capacity(file.getSize());
					break;
				case 1:
					dao.setImgcontents2_capacity(file.getSize());
					break;
				case 2:
					dao.setImgcontents3_capacity(file.getSize());
					break;
				case 3:
					dao.setImgcontents4_capacity(file.getSize());
					break;
				}
				
				file.transferTo( new File( Server.filePath + savname) );
				changeImgNo.add(i + 1);
			}
		}
		return changeImgNo;
	}
	
	//수정할 경품 정보 가져오기.
	@SuppressWarnings("unused")
	private HashMap<String, Object> getGiftForUpdate(ContentDao conDao, ContentDao beforeCon) throws Exception {
		HashMap<String, Object> map = new HashMap<String, Object>();
		for(int i = 0; i < 3; i++) {
			GiftDao gift = new GiftDao();
			Object giftId = beforeCon.getClass().getMethod("getGift" + (i+1)).invoke(beforeCon);
			
			//새로 선택한 이미지가 없고, 기존에도 입력이 안되어있다면 null.
			if(conDao.getGiftfiles().get(i).getOriginalFilename().equals("")) {
				if(giftId == null || giftId.equals("")) {
					map.put("gift" + i, null);
					continue;
				}
			} 
			//입력한 경우.
			else {
				gift.setContents_no(conDao.getNo());
				gift.setName((String)conDao.getClass().getMethod("getGift" + (i+1)).invoke(conDao));
				gift.setPrice((Integer)conDao.getClass().getMethod("getGift" + (i+1) + "_price").invoke(conDao));
				
				MultipartFile file = conDao.getGiftfiles().get(i);
				if(!file.getOriginalFilename().equals("")) {
					gift.setImg_oriname(file.getOriginalFilename());
					gift.setImg_savname(String.valueOf( System.currentTimeMillis( ) ) + "_" + ran.nextInt( 100 ) + "_" + i + "_" + beforeCon.getCo_id() + ".jpg");
					file.transferTo(new File(Server.filePath + gift.getImg_savname()));
				} else {
					gift.setImg_oriname(null);
					gift.setImg_savname(null);
				}
				
				//새로 입력했을경우.
				if(giftId == null || giftId.equals("")) {
					//insert 처리.
					gift.setId(String.valueOf(System.currentTimeMillis() + i));
				} 
				//기존 내용 업데이트.
				else {
					//update 처리.
					gift.setId(giftId.toString());
				}
			}
			
			map.put("gift" + i, gift);
		}
		return map;
	}
}
